import { getMeterInfoApi, updateMeterApi } from '@/api/meter';
import { getDeviceStatus } from '@/api/event';
import convertToTreeData from '@/utils/convertToTreeData';
import { getMetersByLevel } from '@/utils/getMetersByLevel';
import { defineStore } from 'pinia'
import { ref, shallowRef, computed } from 'vue'

// 定义层级顺序
const LEVEL_ORDER = {
    'Ⅰ': 1, 'Ⅱ': 2, 'Ⅲ': 3, 'Ⅳ': 4, 'Ⅴ': 5, 'Ⅵ': 6, 'Ⅶ': 7, 'Ⅷ': 8, 'Ⅸ': 9, 'Ⅹ': 10, 'Ⅺ': 11
};

// 排序函数
function sortMeterList(list) {
    return [...list].sort((a, b) => {

        const [levelA, seqA] = a.meter_code.split('-');
        const [levelB, seqB] = b.meter_code.split('-');
        // 获取层级顺序
        const levelOrderA = LEVEL_ORDER[levelA] || 0;
        const levelOrderB = LEVEL_ORDER[levelB] || 0;

        // 如果层级不同，按层级排序
        if (levelOrderA !== levelOrderB) {
            return levelOrderA - levelOrderB;
        }
        // 如果层级相同，按编号排序
        return parseInt(seqA) - parseInt(seqB);
    });
}

export const useMeterStore = defineStore('meter', () => {
    const treeDataForChart = shallowRef([]);
    const meterList = ref([]);
    const meterLevels = ref([]);
    let currentMeter = ref(null);
    let currentSelectedType = ref(1);

    async function fetchMeterList(params) {
        params = {
            type: currentSelectedType.value,
            ...params
        }
        const res = await getMeterInfoApi(params);
        if (res.code !== 200) {
            throw new Error(res.message || '获取表计列表失败');
        }
        // 对列表进行排序
        meterList.value = sortMeterList(res.data);
        treeDataForChart.value = await convertToTreeData(meterList.value);
        meterLevels.value = getMetersByLevel(treeDataForChart.value);
        return res;
    }

    // 更新所有设备的状态 1.离线，2.在线，3.异常
    async function updateMeterStatus(params) {
        try {
            const res = await getDeviceStatus(params);
            if (res.code === 200 && Array.isArray(res.data.status)) {
                meterList.value = meterList.value.map(meter => {
                    const statusInfo = res.data.status.find(s => s.meter_id === meter.id);
                    return {
                        ...meter,
                        status: statusInfo?.status || 2, // 如果没找到状态信息，默认为在线(2)
                    };
                });
                // 更新状态后重新排序
                meterList.value = sortMeterList(meterList.value);
                treeDataForChart.value = await convertToTreeData(meterList.value);
                meterLevels.value = getMetersByLevel(treeDataForChart.value);
            }
            return res;
        } catch (error) {
            console.error('获取设备状态失败:', error);
            return null;
        }
    }


    async function addMeterLocation(location) {
        let params = {
            ...currentMeter.value,
            ...location
        }
        let res = await updateMeterApi(params);
        if (res.code !== 200) {
            throw new Error(res.message || '获取表计列表失败');
        }
    }

    function setCurrentMeter(meter) {
        currentMeter.value = meter;
    }
    function setCurrentSelectedType(type) {
        currentSelectedType.value = type;
    }

    function getMeterByMeterId(meterId) {
        const meter = meterList.value.find(item => item.id === meterId);
        return meter;
    }
    return {
        treeDataForChart,
        meterLevels,
        meterList,
        fetchMeterList,
        updateMeterStatus,
        currentMeter,
        setCurrentMeter,
        addMeterLocation,
        currentSelectedType,
        setCurrentSelectedType,
        getMeterByMeterId
    };
});
